package com.ailanyin.common.security.filter;

import com.ailanyin.common.security.constants.SecurityConstant;
import com.ailanyin.common.security.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/21 0021 下午 14:13
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 为了保证 SecurityContext 上下文中 userInfo 是最新的
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {

        if (SecurityConstant.SECURITY_WHITELIST.contains(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        // The part after "Bearer "
        String authHeader = request.getHeader(SecurityConstant.TOKEN_HEADER);
        if (authHeader != null && authHeader.startsWith(SecurityConstant.TOKEN_HEAD)) {
            String authToken = authHeader.substring(SecurityConstant.TOKEN_HEAD.length());
            if (TokenUtil.validateToken(authToken)) {
                String username = TokenUtil.getUserNameFromToken(authToken);
                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
